package com.waterfairy.getipsocket;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @user xuchangwei
 * @date 2021/8/26上午10:33
 * @mail 995637517@qq.com
 * @info 本地DNS配置
 */
public class DnsMasq {
    private static DnsMasq dnsMasq = new DnsMasq();

    public static DnsMasq getInstance() {
        return dnsMasq;
    }

    public boolean replaceIp(String address, String ip) throws IOException {
        File file = new File("/home/dnsmasq/dnsmasq.conf");
        FileReader fileReader = new FileReader(file);
        StringBuilder content = new StringBuilder();
        char[] bytes = new char[1024];
        int length = 0;
        while ((length = fileReader.read(bytes)) != -1) {
            content.append(new String(bytes, 0, length));
        }
        fileReader.close();
        try {
            String source = content.toString();
            String temp = editContent(source, address, ip);
            if (!source.equals(temp)) {
                //有替换
                FileWriter fileWriter = new FileWriter(file);
                fileWriter.write(temp);
                fileWriter.flush();
                fileWriter.close();
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public String editContent(String content, String address, String ip) throws Exception {
        int nextIndex;
        String mark = "address=/" + address + "/";
        if ((nextIndex = content.indexOf(mark)) != -1) {
            String nextLine = "\n";
            int nextLineIndex = content.indexOf(nextLine, nextIndex);
            if (nextLineIndex == -1) nextLineIndex = content.length();
            return content.substring(0, nextIndex + mark.length()) + ip + content.substring(nextLineIndex);
        }
        throw new Exception("数据错误");
    }

    public static void main(String[] args) {
        try {
            System.out.println(DnsMasq.getInstance().editContent("log-queries\n" +
                    "no-resolv\n" +
                    "server=114.114.114.114\n" +
                    "address=/dns.waterfairy.xyz/223.167.75.252", "dns.waterfairy.xyz", "223.167.75.220"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
